import flet as ft
import csv
from io import StringIO
from services.device_service import DeviceService


class SettingsPage:
	def __init__(self, page):
		self.page = page
		self.service = DeviceService()
		self.build()
	
	def build(self):
		# 设备类型管理
		self.device_type_input = ft.TextField(label="新增设备类型", hint_text="输入新设备类型")
		self.device_types_list = ft.ListView(expand=True)
		self._load_device_types()
		
		# 数据导出
		self.export_format = ft.Dropdown(
			label="导出格式",
			options=[ft.dropdown.Option("CSV"), ft.dropdown.Option("Excel")],
			value="CSV"
		)
		
		self.view = ft.Tabs(
			selected_index=0,
			tabs=[
				ft.Tab(
					text="设备类型管理",
					content=ft.Column([
						ft.Text("设备类型管理", size=20),
						ft.Row([
							self.device_type_input,
							ft.ElevatedButton("添加", on_click=self.add_device_type)
						]),
						ft.Divider(),
						ft.Text("现有设备类型:", size=16),
						self.device_types_list
					], spacing=15)
				),
				ft.Tab(
					text="数据导出",
					content=ft.Column([
						ft.Text("数据导出", size=20),
						self.export_format,
						ft.ElevatedButton("导出全部数据", on_click=self.export_data)
					], spacing=15)
				)
			]
		)
	
	def _load_device_types(self):
		# 从服务层获取设备类型
		self.device_types_list.controls.clear()
		types = ["手机", "平板", "手表", "扫描笔"]  # 示例数据，应从数据库获取
		for t in types:
			self.device_types_list.controls.append(
				ft.ListTile(
					title=ft.Text(t),
					trailing=ft.IconButton(
						icon=ft.icons.DELETE,
						data=t,
						on_click=self.delete_device_type
					)
				)
			)
		self.page.update()
	
	def add_device_type(self, e):
		new_type = self.device_type_input.value.strip()
		if new_type:
			# 调用服务层添加设备类型
			self.device_type_input.value = ""
			self._load_device_types()
			self.page.show_snack_bar(
				ft.SnackBar(ft.Text(f"成功添加设备类型: {new_type}", color=ft.colors.GREEN_200))
			)
	
	def delete_device_type(self, e):
		device_type = e.control.data
		# 调用服务层删除设备类型
		self._load_device_types()
		self.page.show_snack_bar(
			ft.SnackBar(ft.Text(f"已删除设备类型: {device_type}", color=ft.colors.RED_200))
		)
	
	def export_data(self, e):
		try:
			data = self.service.get_all_records()
			
			if self.export_format.value == "CSV":
				output = StringIO()
				writer = csv.writer(output)
				# 写入表头
				writer.writerow(["设备名称", "类型", "对方信息", "借出日期", "状态"])
				# 写入数据
				for item in data:
					writer.writerow([
						item["device_name"],
						item["device_type"],
						item["counterpart"],
						item["borrow_date"],
						"已归还" if item["status"] else "未归还"
					])
				
				# 保存文件
				self.page.download(
					filename="device_records.csv",
					content=ft.Text(output.getvalue()),
					mime_type="text/csv"
				)
			
			self.page.show_snack_bar(
				ft.SnackBar(ft.Text("导出成功!", color=ft.colors.GREEN_200))
			)
		except Exception as ex:
			self.page.show_snack_bar(
				ft.SnackBar(ft.Text(f"导出失败: {str(ex)}", color=ft.colors.RED_200))
			)
